using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Globalization;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Cache;
namespace Test {
	class Touch {
		static void MainX() {
			FileInfo fi=new FileInfo(@"");
			DateTime dat=new DateTime(2014,5,14,10,42,13);
			fi.CreationTime=dat;
			fi.LastAccessTime=dat;
			fi.LastWriteTime=dat;
		}
		static void MainC() {
			DAL dir=new DAL("pon-wpsq16-db","directory");
			DataTable tab=dir.Query("select RecordId,Description from DirPickWalkDetail where Description like '%'+char(26)+'%'");
		}

		static void MainT() {
			WebRequest objRequest=WebRequest.Create("http://quote.yahoo.com/d/quotes.csv?s=NXT.L&d=t&f=sl1");
			objRequest.Proxy.Credentials=CredentialCache.DefaultNetworkCredentials;
			//objRequest.ImpersonationLevel=System.Security.Principal.TokenImpersonationLevel.None;
			WebResponse objResponse=objRequest.GetResponse();
			string ret="";
			using(StreamReader sr=new StreamReader(objResponse.GetResponseStream()))
				ret=sr.ReadToEnd();
		}
		static int Mask(int i) {
			string s=i.ToString();
			int res=0;
			foreach(char ch in s)
			{
				res^=int.Parse(ch.ToString());
			}
			if(res>9)
				res=Mask(res);
			return res;
		}
		static void MainB() {
			string str=File.ReadAllText(@"c:\");
			string[] arr=Nod.Dbls(str,"<message>");
			foreach(string msg in arr)
			{
				Console.WriteLine(Nod.Rx(msg,"<body>(.+?)</body>"));
			}
		}

		static void MainY() {
			DAL dir=new DAL("pon-wpsq16-db","directory");
			DataTable bsl=dir.Query("select left(PosNumber,6)sku,price,count(*)[count] from dirParcelDetail(nolock) group by left(PosNumber,6),price having count(*)>800 order by count desc");
			WebClient cli=new WebClient();
			int count=1;
			foreach(DataRow row in bsl.Rows)
			{
				string item=row["sku"].ToString();
				string cnt=row["count"].ToString();
				string price=row["price"].ToString();
				string str=cli.DownloadString(string.Format("http://www.next.co.uk/search?w={0}",item));
				List<string> imgs=new List<string>();
				foreach(Match mat in Regex.Matches(str,"src=\"(.+?shotview.+?\\.jpg)\""))
					imgs.Add(mat.Groups[1].Value);
				if(imgs.Count==1)
				{
					Bitmap bmp=(Bitmap)Bitmap.FromStream(cli.OpenRead(imgs[0]));
					Graphics gr=Graphics.FromImage(bmp);
					string printText=string.Format("#{0:000}:{1}({2})",count,cnt,price);
					SizeF siz=gr.MeasureString(printText,new Font("Tahoma",12));
					RectangleF rect=new RectangleF(new PointF(1,1),siz);
					gr.FillRectangle(new SolidBrush(Color.FromArgb(150,Color.LightYellow)),rect);
					gr.DrawString(printText,new Font("Tahoma",12),Brushes.Black,1,1);
					bmp.Save(string.Format("img//{0:000}_{1}.png",count,item),ImageFormat.Png);
					Console.WriteLine(item);
					count++;
				}
				else
				{
				}
			}
		}


		static void MainO() {
			//Stat usrs=new Stat();
			//TeamFoundationServer tfs=TeamFoundationServerFactory.GetServer(@"pon-wpas01\WHSCollection"/*"http://pon-wpas01:8080/tfs"*/);
			//VersionControlServer vcs=(VersionControlServer)tfs.GetService(typeof(VersionControlServer));
			////Workspace[] arr=vcs.QueryWorkspaces(null,vcs.AuthorizedUser,Environment.MachineName);
			//System.Collections.IEnumerable enumerable=vcs.QueryHistory(@"$/",VersionSpec.Latest,0,RecursionType.Full,"",null,VersionSpec.Latest,Int32.MaxValue,true,false);
			//foreach(Changeset chg in enumerable)
			//{
			//  usrs.Add(chg.Committer);
			//  //Console.WriteLine(chg.CreationDate+" - "+chg.Committer+" - "+chg.Comment);
			//}
		}
		static void MainG() {
			//Rectangle bounds=Screen.GetBounds(Point.Empty);
			//using(Bitmap bitmap=new Bitmap(bounds.Width,bounds.Height))
			//using(Graphics g=Graphics.FromImage(bitmap))
			//  g.CopyFromScreen(Point.Empty,Point.Empty,bounds.Size);
			//bitmap.Save("test.png",ImageFormat.Png);
			CultureInfo culture=(CultureInfo)CultureInfo.CurrentCulture.Clone();
			culture.DateTimeFormat.ShortDatePattern="yyyy-MM-dd";
			culture.DateTimeFormat.LongTimePattern="HH:mm:ss";
			Thread.CurrentThread.CurrentCulture=culture;
			DAL dal2=new DAL("pon-wpsq16-db.directory".Split('.'));
			//string[] arr=File.ReadAllLines("tfile.txt");
			//Console.Write(str+" ");
			DataTable data=dal2.Query(@"SELECT b.RecordID[BatchId],b.Batch[BatchNo],w.RecordID WalkId,pd.PosNumber,pd.ColourSize,pd.Description,pd.CustomerNumber,pd.InvoiceNumber,pd.DeliveryNoteNumber,
b.CreatedDate[BatchCreated],wd.PickTime[PickedTime],wd.Location,wd.PickedByBonusNumber,
ns.Inserted[NoStockInserted],substring(ns.AlternateLocation,1,6)[NsAltLoc],ns.PickedBy[NsPickedBy],pck.EventDate[PackingStarted],p.PackingStation,mis.EventDate[RegAtMissingItems],pd.MIOrigStatus,p.PigeonHole,p.ParcelAtMI,
case when DeliveryDay ='ANY' and DeliveryTime ='ANY' then 'Y' else 'N' end[AnyAny],case when p.Status='C' and pld.CustomerNo is null then 'Y' else 'N' end[PickedFromPH]
from DirBatch b(nolock)
join DirPickWalk w(nolock)on b.RecordID=w.BatchID
join DirPickWalkDetail wd(NOLOCK)on w.RecordID = wd.PickWalkId
join dirParcelDetail pd(nolock)on pd.CustomerNumber=wd.CustomerNumber and pd.InvoiceNumber=wd.InvoiceNumber
join dirParcel p(nolock)on p.RecordID=pd.ParcelRecordId
left join dirNoStock ns(nolock) on ns.CustomerNumber=wd.CustomerNumber and ns.InvoiceNumber=wd.InvoiceNumber
left join (select DeliveryNoteNumber,min(EventDate)EventDate from dirParcelLog(nolock)where EventType=2 group by DeliveryNoteNumber
)pck on pck.DeliveryNoteNumber =pd.DeliveryNoteNumber
left join (select DeliveryNoteNumber,min(EventDate)EventDate from dirParcelLog(nolock)where EventType in(26,31)group by DeliveryNoteNumber)mis on mis.DeliveryNoteNumber=pd.DeliveryNoteNumber
left join (select CustomerNo,InvoiceNo from dirPickListDetail(nolock)group by CustomerNo,InvoiceNo)pld on pld.CustomerNo=wd.CustomerNumber and pld.InvoiceNo=wd.InvoiceNumber
where p.Warehouse = 'X' and  b.Batch =30 and convert(char(10),b.CreatedDate,20)='2012-09-22'
order by mis.EventDate desc");
			CSV(data,"C:\\MiReport20120828.csv");
		}
		static void CSV(DataTable tab,string filename) {
			StringBuilder sb=new StringBuilder();
			int cntc=0;
			string[] cols=new string[tab.Columns.Count];
			foreach(DataColumn col in tab.Columns)
				cols[cntc++]=col.ColumnName;
			sb.AppendLine(string.Join(",",cols));
			foreach(DataRow row in tab.Rows)
			{
				string[] arr=new string[row.ItemArray.Length];
				int cnt=0;
				foreach(object obj in row.ItemArray)
					arr[cnt++]=obj.ToString().Trim();
				sb.AppendLine(string.Join(",",arr));
			}
			System.IO.File.WriteAllText(filename,sb.ToString());
		}
		static void MainA() {
			int sum=0;
			DAL pwdal=new DAL("pon-wpsq09-db","pwms");
			DAL dirDal=new DAL("pon-wpsq16-db","directory");
			DataTable pwtab=pwdal.Query("select top 50000 accountNo,deliverypostcode  from tblWhseOrderView(nolock) ORDER BY NextReferenceID DESC");
			string whin=DAL.CsvColumn(pwtab,"accountNo",true);
			DataTable CustQty=dirDal.Query(@"select prc.CustomerNumber,count(*)cnt from dirparcel prc(nolock)
join dirParcelDetail det(nolock) on prc.RecordID=det.ParcelRecordId where prc.CustomerNumber in({0})
group by prc.CustomerNumber order by 2 desc",whin);
			Stat codOrd=new Stat();
			foreach(DataRow row in pwtab.Rows)
			{
				string acc=row["accountNo"].ToString();
				string cod=row["deliverypostcode"].ToString();
				//int i=(int)dirDal.Scalar("select count(*) from dirparcel where CustomerNumber='{0}'",acc);
				string strqty=CustQty.Compute("sum(cnt)","CustomerNumber='"+acc+"'").ToString();
				int i;
				if(int.TryParse(strqty,out i))
				{
					if(i>0)
					{
						sum+=i;
						codOrd.Add(acc,i);
					}
				}
			}
		}
		static void MainW() {
			Stat ustat=new Stat();
			DirectoryInfo di=new DirectoryInfo(@"C:\inetpub\logs\LogFiles\W3SVC1");
			foreach(FileInfo fi in di.GetFiles())
			{
				try
				{
					string[] lines=File.ReadAllLines(fi.FullName);
					foreach(string line in lines)
					{
						string[] arr=line.Split(' ');
						if(arr.Length==14)
							if(!arr[7].ToLower().Contains("pziarek")&&arr[7]!="-")
								ustat.Add(arr[7].ToLower());
					}
				}
				catch { }
			}
		}
		static void MainE() {
			Dictionary<int,int> stat=new Dictionary<int,int>();
			for(int i=456789;i<4567890;i++)
			{
				int msk=Mask(i);
				if(!stat.ContainsKey(msk))
					stat.Add(msk,1);
				else
					stat[msk]++;
			}
		}
		static void MainQ() {
			UdpClient cl=new UdpClient(20000);
			IPEndPoint remoteEP=new IPEndPoint(IPAddress.Any,0);
			while(true)
			{
				byte[] arr=cl.Receive(ref remoteEP);
				Console.WriteLine(Encoding.ASCII.GetString(arr));
			}
		}
		static void MainXc() {
			DAL dal=new DAL("pon-wpsq08-db.returns".Split('.'));
			string table="Debit_daily_transfer_archive";
			int start=(int)dal.Scalar("select min(id) from {0}(nolock)",table);
			int step=10000;
			for(int id=start;id<=23273600;id+=step)
			{
				System.Diagnostics.Stopwatch sw=System.Diagnostics.Stopwatch.StartNew();
				int del=dal.NonQry("delete {0} where ID<{1} and created<getdate()-365",table,id);
				sw.Stop();
				DateTime dat=(DateTime)dal.Scalar("select min(created)dat from {0}(nolock)",table);
				Console.WriteLine(string.Join("; ",new string[] { id.ToString(),del.ToString(),sw.Elapsed.ToString(),dat.ToString("yyyy-MM-dd HH:mm:ss") }));


			}
		}
	}
}
